package com.gsx.controller;

import com.gsx.bean.Cart;
import com.gsx.bean.User;
import com.gsx.service.CartService;
import com.gsx.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Description TODO
 * @Authoe gsx
 * @Date 2021/04/02 下午 3:03
 **/
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private CartService cartService;

    /**
     * 用户登录
     * 如果session中有购物车信息将信息 设置到数据库中
     * @param name
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(String name, String password,HttpServletRequest request){
        if (name!=null&&password!=null){
            User user = userService.getUserByNameAndPassword(name, password);
            if (user!=null){
                HttpSession session = request.getSession();
                session.setAttribute("user", user );
                Cart cart = (Cart)session.getAttribute("cart");
                if (cart!=null){
                    cart.setFkCartUserId(user.getUserId());
                    cartService.setCart(cart);
                    session.setAttribute("cart",null);
                }
                return  "/ssm/html/01-index.html";
            }
        }
            return "false";
    }

    /**
     * 获得session中的用户信息
     * @param request
     * @return
     */
    @RequestMapping("/getUser")
    @ResponseBody
    public User getUser(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        return user;
    }
}
